package net.zjitc.securitycodepermission.config;

import jakarta.annotation.Resource;
import net.zjitc.securitycodepermission.filter.CaptchaFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @author 罗翼侨
 * @date 2025/3/4 14:05
 */
@EnableMethodSecurity
@Configuration
public class SecurityConfig {
    @Resource
    private CaptchaFilter captchaFilter;
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
        return httpSecurity
                .formLogin(
                        formLogin -> {
                            formLogin
                                    .loginProcessingUrl("/user/login")
                                    .loginPage("/toLogin")
                                    .successForwardUrl("/welcome1");//定制登录页（thymeleaf）
                        }
                )
                .authorizeHttpRequests((authorizeHttpRequests)->{
                    authorizeHttpRequests
                            .requestMatchers("/toLogin","/common/captcha").permitAll()
                            .anyRequest().authenticated();
                })
                .addFilterBefore(captchaFilter, UsernamePasswordAuthenticationFilter.class)
                .build();
    }
}